<?php

/**
 * block message of user whom you don't like
 * 
 * @property int $block_message_id 
 * @property int $user_block 
 * @property int $blocked_user
 * @property int $time_created
 */
class BlockMessage extends CActiveRecord {

    public $email;

    const TOTAL_RECORD = 30;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{block_messages}}';
    }

    public function rules() {
	return array(
	    array('blocked_user', 'required', 'message' => 'Email is not existed'),
	    array('block_message_id, user_block, time_created, email', 'safe')
	);
    }

    public function relations() {
	parent::relations();
	return array(
	    'userBlock' => array(self::BELONGS_TO, 'User', 'user_block'),
	    'blockedUser' => array(self::BELONGS_TO, 'User', 'blocked_user')
	);
    }

    public function search($id) {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;
	$criteria->with = array("blockedUser");
	$criteria->alias = 't';
	$criteria->addCondition('t.user_block=' . $id);
	$criteria->compare('blockedUser.email', $this->email, true);
	//order
	$criteria->order = 't.time_created DESC';

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    )
	));
    }

    /**
     * delete blocked user
     * 
     * @param int $id 
     */
    public static function deleteBlock($id, $idUser) {
	db()->createCommand('DELETE FROM {{block_messages}} WHERE block_message_id = ' . $id)->execute();

	//clear cache
	$aIdsBlock = Yii::app()->cache->get('aIdsBlocked' . $idUser);
	if ($aIdsBlock !== FALSE) {
	    Yii::app()->cache->delete('aIdsBlocked' . $idUser);
	}
    }

    /**
     * 
     */
    public static function getIdsBlock($id) {
	$aIdsBlock = Yii::app()->cache->get('aIdsBlocked' . $id);
	if ($aIdsBlock === FALSE) {
	    $aIdsBlock = array();
	    $aIds = db()->createCommand('SELECT * FROM {{block_messages}} WHERE user_block = ' . $id)->queryAll();
	    foreach ($aIds as $item) {
		$aIdsBlock[] = $item['blocked_user'];
	    }
	    Yii::app()->cache->set('aIdsBlocked' . $id, $aIdsBlock);
	}
	return $aIdsBlock;
    }

    public function beforeSave() {
	parent::beforeSave();
	$this->time_created = date('Y-m-d', time());
	return true;
    }

    public function afterSave() {
	parent::afterSave();

	//clear cache
	$aIdsBlock = Yii::app()->cache->get('aIdsBlocked' . $this->user_block);
	if ($aIdsBlock !== FALSE) {
	    Yii::app()->cache->delete('aIdsBlocked' . $this->user_block);
	}
    }

}

